package cn.virens.packet.handler;

import org.tio.core.ChannelContext;

import cn.virens.App;
import cn.virens.TioUtil;
import cn.virens.app.common.SQL;
import cn.virens.common.ByteUtil;
import cn.virens.packet.ReadPacket;
import cn.virens.packet.WritePacket;

public class ReportSensorHandler extends AbstractHandler {

	@Override
	public void read(ReadPacket packet, ChannelContext channelContext) {
		logger.debug("接收数据包");
		TioUtil.heartTimes(channelContext, (t) -> t.incrementAndGet());
		TioUtil.heartIdle(channelContext, (t) -> t.getAndSet(0));

		//解析数据包
		//		Integer type = ByteUtil.toInt(packet.data(0, 1));//事件类型
		String imsi = TioUtil.imei(channelContext);//imei
		Integer device_status = ByteUtil.toInt(packet.data(1, 1));//设备状态
		Float surplus_flow = (float) ByteUtil.toInt(packet.data(2, 2));//剩余流量
		Float totle_flow = (float) ByteUtil.toInt(packet.data(6, 2));//累计流量
		Float raw_water_tds = (float) ByteUtil.toInt(packet.data(14, 2));//原水tds值
		Float pure_water_tds = (float) ByteUtil.toInt(packet.data(16, 2));//纯水tds值

		if (device_status == 4 || device_status == 5 || device_status == 6) {
			App.db().executeUpdate(SQL.WARING_DATA_IN, imsi);
		} else {
			App.db().executeUpdate(SQL.SENSOR_DATA_IN, imsi, raw_water_tds, pure_water_tds, totle_flow, totle_flow, surplus_flow, device_status, "");
		}
		//构建应答包数据，数据上报的应答
		WritePacket writePacket = WritePacket.of(packet, "8004");
		//发送应答包
		TioUtil.write(channelContext, writePacket);
	}
}
